package com.jinbei.aop;

import com.alibaba.fastjson.JSONObject;
import com.jinbei.common.Enum.ConstantsEnum;
import com.jinbei.common.base.ResponseBaseEntity;
import com.jinbei.common.contants.Contants;
import com.jinbei.common.util.AuthorizationUtil;
import com.jinbei.common.util.CookieUtil;
import com.jinbei.domain.User;
import com.jinbei.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;

/**
 * @author zflu
 * 切面拦截 权限
 * Created by lucky on 2018/7/10.
 */
@Order(3)
@Aspect
@Component
public class AspectAuthor {

    private final Logger logger = LoggerFactory.getLogger(AspectAuthor.class);


    @Autowired
    private UserService userService;

    /**
     * @author zflu
     * @Description   权限注解切面
     * @date 2018/7/10 11:32
     * @param
     * @return void
     */
    @Pointcut("@annotation(com.jinbei.common.annotation.AuthorAnnotation)")
    public void pointCutAnnotation(){
    }

    /**
     * @author zflu
     * @Description 拦截加注解的方法
     * @date 2018/7/10 11:44
     * @param point
     * @return java.lang.Object
     */
    @Around("pointCutAnnotation()")
    public Object interceptAuthor(ProceedingJoinPoint point) throws Throwable{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        boolean isFlag = (boolean) request.getAttribute(Contants.FLAG);
        //如果不需要授权就放行
        if(!isFlag){
            return point.proceed();
        }

        //获取请求url
        String requestUrl = null;
        if(request.getRequestURI().toString().indexOf(Contants.SYSTEM_NAME) > -1){
            requestUrl = request.getRequestURI().toString().split(Contants.SYSTEM_NAME)[1];
        }else{
            requestUrl = request.getRequestURI().toString();
        }

        //获取授权code
        String code = CookieUtil.getCookie(request,Contants.AUTHORIZATION);
        if(StringUtils.isBlank(code)){
            return ResponseBaseEntity.setResultError(ConstantsEnum.ERROR_501);
        }
        JSONObject json = AuthorizationUtil.getUserByAuthorization(code);
        //授权失败
        if(json.isEmpty()){
            return ResponseBaseEntity.setResultError(ConstantsEnum.ERROR_501);
        }
        String password = (String) json.get(Contants.PASSWORD);
        String loginName = (String) json.get(Contants.LOGIN_NAME);
        //判断是否有权限
        boolean flag = true;

        try {
            User user = userService.queryUserByLoginName(loginName);
            //为密码加盐
            String _password = user.getPassword() + Contants.DECODER_KEY;
            if(user == null || !_password.equals(password)){
                return ResponseBaseEntity.setResultError(ConstantsEnum.ERROR_501);
            }
            //获取该用户所有的权限 匹配
            HashSet<String> hashSet = userService.queryUserAuthorUrl(Integer.valueOf(user.getUserId()));

            if(hashSet.size() > 0 && StringUtils.isNotBlank(requestUrl)){
                flag = hashSet.contains(requestUrl);
            }else{
                flag = false;
            }
            if(!flag){
                return  ResponseBaseEntity.setResultError(ConstantsEnum.Author_Error301);
            }
        }catch (Exception e){
            logger.error("查询用户授权 url 失败......{}",e);
            return  ResponseBaseEntity.setResultError(ConstantsEnum.ERROR_500);
        }

        return point.proceed();
    }
}
